<template>
  <div>
    <div class="mainCon">
      <div class="containercontent">
        <!--<div class="penalrow selectw100 opabsolute">
      		<el-button type="primary" size="mini" @click="popupShow=true;">添加计量单位</el-button>
      	</div>-->
        <div class="seachTip selectw100">
          <div class="inlineblock verticalmiddle infoitem">
            <div class="inlineblock verticalmiddle">
              名称
            </div>
            <div class="inlineblock verticalmiddle informationItem">
              <el-input v-model="searchName" size="mini" placeholder="计量单位名称" @keyup.enter.native="readUnitList(unitQuery,'search')"></el-input>
            </div>
          </div>
          <div class="inlineblock basicRightDistanceA searchIcon">
            <el-button size="mini" @click="readUnitList(unitQuery,'search')">搜索</el-button>
          </div>
          <div class="inlineblock basicRightDistanceA searchIcon">
            <el-button size="mini" @click="emptySearch()">清空</el-button>
          </div>
        </div>
        <div class="separaterowTable">
          <div class="tableTittle">
            <div><span class="fontImpact">1</span><span>计量单位</span></div>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addUnit" style="float:right" v-if="userOpernation.add.display">添加计量单位</el-button>

          </div>
          <el-table :data="unitTableDate" style="width: 100%" size="mini" class="tableCon">
            <el-table-column label="序号" min-width="50px">
              <template slot-scope="scope">
                {{scope.$index+(unitQuery.page - 1) * unitQuery.pageCount + 1}}
              </template>
            </el-table-column>
            <el-table-column property="cname" label="名称" :show-overflow-tooltip='true' min-width="100px">
            </el-table-column>
            <!--<el-table-column
                property="code"
                label="代码"
                min-width="200px">
              </el-table-column>-->
            <el-table-column property="ename" label="英文名" min-width="100px">
            </el-table-column>
            <el-table-column property="UnitType" label="类型" min-width="100px" :formatter="util.tableFormatter">
            </el-table-column>
            <el-table-column property="doSi" label="是否国际单位" min-width="100px" :formatter="doSiFormatter">
            </el-table-column>
            <!--<el-table-column property="status" label="状态" min-width="120px" :formatter="formatter">
            </el-table-column>-->
            <el-table-column label="操作" min-width="100px">
              <template slot-scope="scope">
                <!--<el-button v-if="scope.row.status=='1' && userOpernation.disable.display" type="text" size="mini" @click="isStart(scope.row)">停用</el-button>-->
                <!--<el-button v-if="scope.row.status=='0' && userOpernation.enable.display" type="text" size="mini" @click="isStart(scope.row)">启用</el-button>-->
                <el-button @click="editUnit(scope.row)" type="text" size="mini" v-if="userOpernation.update.display">编辑</el-button>
                <!---->
                <!--<el-button @click="deleteUnit(scope.row)" type="text" size="mini" v-if="scope.row.status=='2'">删除</el-button>-->
              </template>
            </el-table-column>
          </el-table>
          <div class="block changepages">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="unitQuery.page" :page-sizes="[20,30,40]"
              :page-size="unitQuery.pageCount" layout="total, sizes, prev, pager, next, jumper" :total="rowNumber">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <!--<div v-if='popupShow'>
      <unit-add :newOrEdit="newOrEdit" :canEdit="canEdit"></unit-add>
    </div>-->

    <el-dialog :visible.sync="addUnitShow" width="70%" :show-close='false' :closeOnClickModal='false' class="unitDialog">
      <span slot="title" class="dialog-title">
		  	{{newOrEdit=='new'?'新增':'编辑'}}主表单位
			    <el-button @click="resetForm('unitForm')" size="mini" class="popupClose">关闭</el-button>
			  </span>
      <el-form label-width="110px" :inline="false" class="demo-form-inline unitForm" :model="unitForm" :rules="unitrules" ref="unitForm">
        <el-form-item label="名称" prop="cname">
          <el-col :span="22">
            <el-input placeholder="名称" size="mini" v-model="unitForm.cname"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="编码" prop="code" v-if="newOrEdit != 'new'">
          <el-col :span="22">
            <el-input placeholder="编码" size="mini" v-model="unitForm.code" disabled></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="英文名" prop="ename">
          <el-col :span="22">
            <el-input placeholder="英文名" size="mini" v-model="unitForm.ename"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-col :span="22">
            <el-select v-model="unitForm.type" placeholder="请选择" style="width: 100%;" size="mini">
              <el-option v-for="item in unitSelect.itemList" :key="item.code" :label="item.name" :value="item.code">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="是否国际单位" prop="doSi">
          <el-col :span="22">
            <el-select v-model="unitForm.doSi" placeholder="请选择" style="width: 100%;" size="mini">
              <el-option v-for="item in yesorno" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <!--<el-form-item label="状态" v-if="newOrEdit != 'new'">
          <el-col :span="22">
            <el-select v-model="unitForm.status" placeholder="请选择" style="width: 100%;" size="mini" disabled>
              <el-option v-for="item in enableStatus" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>-->
      </el-form>
      <div class="elTab" v-if="newOrEdit == 'edit'">
        <el-tabs style="width: 100%;" v-model="activeName">
          <el-tab-pane label="换算关系" name="first">

            <el-button @click="addChangeUnit" type="primary" size="mini" style="float:right;margin-bottom:5px">添加</el-button>

            <el-table :data="unitForm.convertBeanList" style="width: 100%" size="mini" class="tableCon" height="calc(100% - 33px)">
              <el-table-column label="序号" min-width="50px">
                <template slot-scope="scope">
                  {{scope.$index+1}}
                </template>
              </el-table-column>
              <el-table-column property="unitCode" label="换算单位" min-width="200px">
                <template slot-scope="scope">
                  <!--unitConvertList-->
                  <el-select v-model="scope.row.unitCode" size="mini" filterable>
                    <el-option v-for="item in unitConvertList" :key="item.code" :label="item.ename" :value="item.code">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column property="value" label="换算率(=主表单位/换算单位)" min-width="100px">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.value" size="mini"  class = "deal" oninput="this.value=this.value.replace(/[^0-9.]+/,'');"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="100px">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="deleteChildUnit(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>

      <span slot="footer" class="dialog-footer">
           <!--<el-button type="primary" v-if = "newOrEdit == 'new' || isStatus == 2 " size="mini">提交</el-button>-->
			    <el-button type="primary" @click="submitForm" size="mini" :disabled="!isRepeat">确 定</el-button>
			    <el-button  size="mini" @click="resetForm('unitForm')">取 消</el-button>
			  </span>
    </el-dialog>
  </div>
</template>

<script>
  import { mapState } from 'vuex'



  export default {
    data() {
      return {
        unitQuery: {
          page: 1, //第几页
          pageCount: 20, //页面得记录条数，
        },
        rowNumber: 0,
        searchName: '',
        unitTableDate: [],
        addUnitShow: false, //添加计量单位弹框
        newOrEdit: 'new',  //是否新增
        canEdit: true, //是否可编辑
        unitForm: {
          name: '',
          ename: '',
          code: '',
          doSi: '',
          type: '',
          convertBeanList: [],
        },
        unitrules: {
          cname: [{ required: true, type: 'string', message: '请填写名称', trigger: 'blur' },],
          ename: [{ required: true, type: 'string', message: '请填写英文名称', trigger: 'blur' },],
          doSi:[{ required: true,  message: '请填写是否国际单位', trigger: 'change' },],
        },
        activeName: "first",
        unitConvertList: [], //可换算的单位列表
        // isStatus:'',

        yesornoValue: '',
        enableStatusValue: '',
        monitorPointBigTypeValue: '',
        sampleTypeValue: '',
        isRepeat: true,


      }
    },
    components: {

    },
    computed: {
      ...mapState(['enableStatus', 'unitSelect', 'yesorno']),
    },
    mounted() {
      this.$store.dispatch('dogetDictionary')
      this.readUnitList(this.unitQuery)
    },
    props: ['userOpernation'],
    watch: {
      unitQuery: {
        handler(val, oldVal) {
          this.readUnitList(this.unitQuery)
        },
        deep: true
      },
    },
    methods: {
      emptySearch() {
        this.searchName = '';
        this.readUnitList(this.unitQuery,'search')
      },
      // 是否国际单位
      doSiFormatter(row, column, cellValue, index) {
        return this.util.changeStatus({ cellValue: cellValue, list: this.yesorno })

      },
      // 过滤状态
      formatter(row, column, cellValue, index) {
        return this.util.changeStatus({ cellValue: cellValue, list: this.enableStatus })

      },
      // 读取计量单位列表
      readUnitList(parp,search) {
        var params = {
          cname: this.searchName,
        }
        if(search !=undefined){
            this.unitQuery.page = 1
            params.page = 1;
						params.pageCount = parp.pageCount;
        }else{
          params.page = parp.page;
					params.pageCount = parp.pageCount;
        }

        this.$http({
          method: 'post',
          apiUrl: '/system/readUnitList.htm',
          params: params,
          isJson: true,
        }).then(res => {
          if (res.code === 0) {
            this.unitTableDate = res.data;
            if (!res.pageinfo) {
              this.rowNumber = 0;
            } else if (res.pageinfo && !res.pageinfo.rowNumber) {
              this.rowNumber = 0;
            } else {
              this.rowNumber = res.pageinfo.rowNumber;
            }
          }

        })
      },
      // 添加计量单位
      addUnit() {
        this.addUnitShow = true;
        this.newOrEdit = 'new';
      },
      editUnit(row) {
        this.convertUnit(row.id, row.type);


        this.$http({
          method: 'post',
          apiUrl: '/system/readUnitById.htm',
          params: { id: row.id },
          isJson: false,
        }).then(res => {
          if(res.code == 0){
            //  for (var i in res.data) {
            //   this.unitForm[i] = res.data[i]

            // };
             this.unitForm = res.data
            this.addUnitShow = true;
            this.newOrEdit = 'edit';
            //
          }

        })

        // this.isStatus = this.unitForm.status;
      },
      //换算单位列表
      convertUnit(id, type) {
        var param = {
          id: id,
          type: type,
        }
        this.$http({
          apiUrl: '/system/readCanUnitConvertList.htm',
          method: 'post',
          params: param,
          isJson: true,
        }).then(res => {
          this.unitConvertList = res.data;
        })
      },
      // 关闭表单
      resetForm(formName) {
        this.$refs[formName].resetFields(); //重置验证
        this.addUnitShow = false;
        this.isRepeat = true;
        this.unitForm = {
          name: '',
          ename: '',
          code: '',
          doSi: '',
          type: '',
          convertBeanList: [],
        };

      },
      // 提交新增和编辑
      submitForm(unitForm) {
        this.$refs.unitForm.validate((valid) => { //表单验证
          if (valid) {
            for (var i in this.unitForm.convertBeanList) {
              this.unitForm.convertBeanList[i].fRef = this.unitForm.id;
              this.unitForm.convertBeanList[i].parentCode = this.unitForm.code;
              for(var j in this.unitConvertList){
                if(this.unitForm.convertBeanList[i].unitCode == this.unitConvertList[j].code){
                  this.unitForm.convertBeanList[i].childId = this.unitConvertList[j].id;
                }
              }

            }
            if (this.newOrEdit == 'new') {
              var url = '/system/addUnit.htm';
              var data = {
                cname: this.unitForm.cname,
                code: this.unitForm.code,
                doSi: this.unitForm.doSi,
                ename: this.unitForm.ename,
                type: this.unitForm.type,
                status: 1,
              }
            } else {
              var url = '/system/updUnit.htm';
              var data = {
                id: this.unitForm.id,
                cname: this.unitForm.cname,
                code: this.unitForm.code,
                doSi: this.unitForm.doSi,
                ename: this.unitForm.ename,
                type: this.unitForm.type,
                convertBeanList: this.unitForm.convertBeanList,
              }
            }
            this.isRepeat = false;
            this.$http({
              method: 'post',
              apiUrl: url,
              params: data,
              isJson: true,
            }).then(res => {
              this.isRepeat = true;
              if (res.code == 0) {
                this.$message({
                  type: 'success',
                  message: '提交成功!'
                });
                this.resetForm('unitForm')
                this.readUnitList(this.unitQuery);

              }

            }).catch(() => {

            });

          } else {
            return false;
          }
        })
      },
      // 删除计量单位
      deleteUnit(row) {
        this.$confirm('是否删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var that = this;
          var param = {
            id: row.id,
          }
          this.$http({
            apiUrl: '/system/deleteUnit.htm',
            method: 'post',
            params: param,
          }).then(res => {
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.readUnitList(this.unitQuery);
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      isStart(row) {
        var msg = row.status == 0 ? "启用" : "停用";
        this.$confirm("是否" + msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            method: 'post',
            apiUrl: '/system/updateUnitStatus.htm',
            params: {
              id: row.id,
              status: row.status == 0 ? 1 : 0,
            },
            isJson: false,
          }).then(res => {
            if (res.code === 0) {
              this.readUnitList(this.unitQuery)
            }

          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消' + msg
          });
        });
      },

      addChangeUnit() { //添加转换单位
        this.unitForm.convertBeanList.push({
          unitCode: null,
          value: null,
        })
      },
      deleteChildUnit(index) {
        this.unitForm.convertBeanList.splice(index, 1)
      },
      handleSizeChange: function (val) {
        this.unitQuery.pageCount = val;
      },
      handleCurrentChange: function (val) {
        this.unitQuery.page = val;
      },

    }
  }

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .seachTip .infoitem {
    width: 380px;
  }

  .seachTip .informationItem {
    width: 300px;
    float: none;
    margin-left: 8px;
  }
</style>
<style>
  .unitDialog .el-dialog {
    height: 75%;
    margin-top: 12vh !important;
  }

  .unitDialog .el-dialog .el-dialog__body {
    height: calc(100% - 85px);
    padding: 10px;
  }

  .unitDialog .el-dialog .el-form-item {
    margin-bottom: 8px;
    width: 49%;
    float: left;
  }

  .unitDialog .el-dialog .unitForm {
    height: 180px;
  }

  .unitDialog .el-dialog .elTab {
    height: calc(100% - 180px)
  }

  .unitDialog .el-dialog .elTab .el-tabs {
    height: 100%
  }

  .unitDialog .el-dialog .elTab .el-tabs .el-tabs__content {
    height: calc(100% - 40px)
  }

  .unitDialog .el-dialog .elTab .el-tabs .el-tabs__content .el-tab-pane {
    height: 100%
  }
</style>
